#!/usr/bin/env python3
# -*- coding: UTF-8 -*-
"""
       app_cherrytree.py
       Code is based on Copyright 2009-2014 Giuseppe Penone <giuspen@gmail.com>

       This program is free software; you can redistribute it and/or modify
       it under the terms of the GNU General Public License as published by
       the Free Software Foundation; either version 3 of the License, or
       (at your option) any later version.

       This program is distributed in the hope that it will be useful,
       but WITHOUT ANY WARRANTY; without even the implied warranty of
       MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
       GNU General Public License for more details.

       You should have received a copy of the GNU General Public License
       along with this program; if not, write to the Free Software
       Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
       MA 02110-1301, USA.
"""

# python gtk3 modules
try:
    # noinspection PyUnresolvedReferences
    from gi.repository import Gtk
    # noinspection PyUnresolvedReferences
    from gi.repository import Gio
except ImportError as e:
    print(e)
    print("Gtk3 libraries could not be found on your system")
    sys.exit(89)  # exit the program

# python standard modules
import sys
# noinspection PyCompatibility
import argparse
import os  # os module
# cherrytree modules
import cherrytree.settings.config  # config object and load and save functions
import cherrytree.debug.debug_stuff as debug  # debug output functions for colour logging
import cherrytree.cons as cons  # const values and the path for the app
from gi.repository import GtkSource, GObject


# noinspection PyCallByClass
class MyApplication(Gtk.Application):  # a Gtk ApplicationWindow
    """
    constructor of the Gtk Application
    init the parent class
    the Gio.ApplicationFlags.HANDLES_COMMAND_LINE flags tells that
    we want to handle the command line and do_command_line will be called
    """

    # noinspection PyTypeChecker
    def __init__(self):
        # debug mode set here - True = ouput debug info - false = no debug output
        self.debugmode = True
        debug.debug_output("class myapplication init method called",
                           "info",
                           "app_cherrytree.py",
                           "do_init()",
                           self.debugmode)
        Gtk.Application.__init__(self,
                                 application_id="org.giuspen.CherryTree5Service",
                                 flags=Gio.ApplicationFlags.HANDLES_OPEN)
        # todo look into this
        # self.set_flags(Gio.ApplicationFlags.HANDLES_COMMAND_LINE | Gio.ApplicationFlags.HANDLES_OPEN) #
        # self.set_application_id("org.giuspen.CherryTree5Service")
        # GLib.set_application_name("Meld")
        # Gtk.Window.set_default_icon_name("meld")
        # windowseditor-notebook
        GObject.type_register(GtkSource.View)  # needed for the gtksourceview to work with the builder
        self.main_window_builder = Gtk.Builder()  # main window builder which holds the objects from the glade file
        self.main_window = None  # the main window object when it is created
        self.arguments = None  # args from the command promt
        # settings
        self.config = cherrytree.settings.config.ConfigSettings  # create object for the config
        # Attributes
        self.tree_right_side = False  # default tree side prefs (left or right)
        self.really_quit = False  # default value for quiting the app (default false)

    def do_startup(self):
        """
        Gtk.Application callback - sets up the application when it first starts
        """
        debug.debug_output("do_startup method called", "info", "app_cherrytree.py", "do_startup()", self.debugmode)
        Gtk.Application.do_startup(self)  # call the application main method
        try:
            debug.debug_output("loadeding glade file", "info", "app_cherrytree.py", "do_startup()", self.debugmode)
            # load the main window object in to the builder
            self.main_window_builder.add_from_file(os.path.join(cons.DATA_DIR, "MainWindow-v3.xml"))

        except Exception as ef:  # the glade file did not load so print out error and exit program
            debug.debug_output("Error 2 - loading the glade file.", "error", "app_cherrytree.py", "do_startup()", True)
            print(ef)  # print error to standard output
            sys.exit(2)  # exit the program

    # noinspection PyBroadException
    def do_activate(self):
        """  Gtk.Application callback - shows the default first window of the application (like a new document).
         This corresponds to the application being launched by the desktop environment.
        """
        debug.debug_output("do_activate method called", "info", "app_cherrytree.py", "do_activate()", self.debugmode)
        # setup main_window
        self.main_window = self.main_window_builder.get_object("MainWindow")  # create gtk window object
        if self.main_window is None:
            debug.debug_output("Error 3 - Could not get the window object from the builder object",
                               "error",
                               "app_cherrytree.py",
                               "do_activate()",
                               self.debugmode)
            sys.exit(3)  # exit the program could not get the object from the builder
        try:
            # load the icon to the window
            self.main_window.set_icon_from_file(os.path.join(cherrytree.cons.ICON_DIR, "cherrytree.png"))
        except Exception as ee:
            debug.debug_output("Error L1 - Could not load the icon image for the main window",
                               "error",
                               "app_cherrytree.py",
                               "do_activate()",
                               self.debugmode)
            print(ee)
        self.main_window.maximize()  # maximize the main window
        self.add_window(self.main_window)  # add window to the app
        self.main_window.show_all()  # show window

    def do_open(self, files, *hint):
        """
        Gtk.Application callback -
        opens files and shows them in a new window.
        This corresponds to someone trying to open a document
        (or documents) using the application from the file browser, or similar.
        :param hint:
        :param files: Gfiles are passed
        :return:
        """
        debug.debug_output("do_open method called", "info", "app_cherrytree.py", "do_open()", self.debugmode)
        debug.debug_output(str(files), "info", "app_cherrytree.py", "do_open()", self.debugmode)
        debug.debug_output(str(hint), "info", "app_cherrytree.py", "do_open()", self.debugmode)

    def do_command_line(self, args):
        """
        Gtk.Application command line handler
        called if Gio.ApplicationFlags.HANDLES_COMMAND_LINE is set.
        must call the self.do_activate() to get the application up and running.
        :param args:
        """
        debug.debug_output("do_command_line method called", "info", "app_cherrytree.py", "do_command()", self.debugmode)
        Gtk.Application.do_command_line(self, args)  # call the default commandline handler

        # make a command line parser
        parser = argparse.ArgumentParser(prog='gui')  # add a -c/--color option
        # parse the command line stored in args, but skip the first element (the filename)
        parser.add_argument('-c', '--color', action='store_true')
        debug.debug_output(args.get_arguments()[0:], "info", "app_cherrytree.py", "do_command()", self.debugmode)
        self.arguments = parser.parse_args(args.get_arguments()[1:])
        debug.debug_output(self.arguments, "info", "app_cherrytree.py", "do_command()", self.debugmode)
        self.do_activate()  # call the main program do_activate() to start up the app
        return 0

    def do_shutdown(self):
        """
        Gtk.Application callback - performs shutdown tasks
        :return:
        """
        debug.debug_output("do_shutdown method called", "info", "app_cherrytree.py", "do_shutdown()", self.debugmode)
        Gtk.Application.do_shutdown(self)  # shut the app down
